package com.tpv.myapp;

import jakarta.mail.*;
import jakarta.mail.event.MessageCountAdapter;
import jakarta.mail.event.MessageCountEvent;
import jakarta.mail.internet.MimeUtility;
import org.eclipse.angus.mail.imap.IMAPFolder;
import org.eclipse.angus.mail.imap.IMAPStore;
import org.eclipse.angus.mail.imap.IdleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

@Component
public class MailPullRunner implements CommandLineRunner {
    private final Logger log = LoggerFactory.getLogger(MailPullRunner.class);
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    @Qualifier("taskExecutor")
    private Executor executor;
    private IMAPFolder inbox;
    private IdleManager idleManager;
    @Override
    public void run(String... args) throws Exception {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) javaMailSender;
        Session session = mailSender.getSession();
        session.setDebug(true);
        IMAPStore store = (IMAPStore) session.getStore("imap");
        store.connect(
            mailSender.getHost(), mailSender.getPort(),
            mailSender.getUsername(), mailSender.getPassword());
        log.info("mail-pull connected:{}", store.isConnected());
        inbox = (IMAPFolder)store.getFolder("INBOX");
        idleManager = new IdleManager(session, executor);
        inbox.open(Folder.READ_WRITE);
        // 添加消息监听器
        reconnect();
    }

    private void reconnect() throws MessagingException {
        inbox.addMessageCountListener(new MessageCountAdapter() {
            @Override
            public void messagesAdded(MessageCountEvent e) {
                Message[] messages = e.getMessages();
                log.info("Number of new messages: {}", messages.length);
                for (Message message : messages) {
                    try {
                        log.info("New message subject: {}", message.getSubject());
                        try {
                            Object content = message.getContent();
                            // 判断内容类型
                            if (content instanceof String) {
                                // 如果是纯文本内容
                                log.info("邮件内容: {}", content);
                            } else if (content instanceof Multipart) {
                                // 如果是多部分内容
                                Multipart multipart = (Multipart) content;
                                for (int i = 0; i < multipart.getCount(); i++) {
                                    Part part = multipart.getBodyPart(i);
                                    Object partContent = part.getContent();

                                    // 处理每个部分的内容
                                    if (partContent instanceof String) {
                                        log.info("邮件部分内容: {}", partContent);
                                    } else {
                                        // 如果是附件或其他非文本内容
                                        log.info("发现附件: {}", MimeUtility.decodeText(part.getFileName()));
                                    }
                                }
                            }
                        } catch (Exception exception) {
                            log.error("Error getting message content: {}", exception.getMessage());
                        }
                        message.setFlag(Flags.Flag.SEEN, true); // 标记为已读
                    } catch (MessagingException ex) {
                        ex.printStackTrace();
                    }
                }
                try {
                    log.info("rewatch:{}", inbox);
                    idleManager.watch(inbox); // keep watching for new messages
                } catch (Exception mex) {
                    log.error("Error watching for new messages: {}", mex.getMessage());
                }
            }
        });
        idleManager.watch(inbox);
    }

    @Scheduled(fixedRate = 3000) // 每隔 3 秒执行一次
    public void performTask() {
        if (inbox != null && idleManager != null) {
            log.info("connected:{}", inbox.isOpen());
            try {
                if (!inbox.isOpen()) {
                    log.info("repen:{}", inbox);
                    inbox.open(Folder.READ_WRITE);
                    reconnect();
                }
            } catch (MessagingException e) {
                log.error("Error opening folder: {}", e.getMessage());
            }
        }

    }
}
